package Ep06_BinaryTree.DFS.T3_0145;

import Ep06_BinaryTree.TreeNode;

import java.util.*;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/4/17 10:33
 * 说明：145 后序遍历  ——  迭代写法
 */

public class PostOrderTraversal_iteration {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            res.add(node.val);
            // 和前序相比只需要交换左和右的入栈顺序，最后再将res数组反转即可
            if (node.left != null){
                stack.push(node.left);
            }
            if (node.right != null){
                stack.push(node.right);
            }
        }
        Collections.reverse(res);
        return res;
    }
}
